package com.mulanweb.api.module.controller;

import com.alibaba.druid.sql.visitor.functions.Char;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.mulanweb.api.module.model.*;
import com.mulanweb.api.module.model.Collection;
import com.mulanweb.db.common.SQLGenerateHelper;
import com.mulanweb.utils.DateUtil;
import com.mulanweb.utils.NumberFormatterUtil;
import com.mulanweb.validator.annotation.ValidateFile;
import com.mulanweb.validator.annotation.ValidateForm;
import org.apache.commons.lang3.StringUtils;

import javax.xml.bind.annotation.XmlAttachmentRef;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2016/8/19.
 */
@ValidateFile
public class CharteredController extends BaseController {



    @ValidateForm
    public void search() {
        Integer typeId = getParaToInt("typeId");
        Integer cityId = getParaToInt("cityId");
        Integer orderBy = getParaToInt("orderBy") !=null?getParaToInt("orderBy"):0;
        Integer receptionNumber = getParaToInt("receptionNumber");;
        Date startDate = DateUtil.strToDate(getPara("startTime"));
        Date endDate = DateUtil.strToDate(getPara("endTime"));

        List<Integer> charteredId = new ArrayList<Integer>();
        SQLGenerateHelper helper = new SQLGenerateHelper("chartered", "create_time");

        if(orderBy == 1){
            //根据价格升序
            helper = new SQLGenerateHelper("chartered", "price");
        }else if(orderBy == 2){
            //根据人气降序
            helper = new SQLGenerateHelper("chartered e"," (SELECT COUNT(*) FROM collection c WHERE c.type_id=24 AND c.target_id=e.id) DESC");
        }else if(orderBy == 3){
            //根据好评降序
            helper = new SQLGenerateHelper("chartered e"," (SELECT SUM(score) FROM content_evaluate c WHERE c.type_id=24 AND c.target_id = e.id) DESC");
        }

        if (StrKit.notNull(startDate) && StrKit.notNull(endDate)) {
            //当开始时间和结束时间同时存在时
            helper.addCondition("start_time", "<=",  DateUtil.dataToHhMmSs(startDate));//加入时间筛选
            helper.addCondition("end_time", ">=", DateUtil.dataToHhMmSs(endDate));//加入时间筛选

            String startStr = DateUtil.dataToYyyyMmDd(startDate);
            String endStr = DateUtil.dataToYyyyMmDd(DateUtil.addDate(endDate));
            //筛选出时间不匹配的包车内容
            while (!(endStr.equals(startStr))) {
                List<DriverJoinSt> list = DriverJoinSt.dao.find("SELECT * FROM driver_join_st WHERE service_time_id=?", DateUtil.getWeekToInt(startDate));
                for (DriverJoinSt tt : list) {
                    List<CharteredJoinType> charteredJoinType = CharteredJoinType.dao.find("select * from chartered_join_type where chartered_id = ?", tt.getCharteredId());
                    for (CharteredJoinType cc : charteredJoinType) {
                        if (cc.getTypeId() == typeId) {
                            charteredId.add(Integer.parseInt(cc.getCharteredId()+""));
                        }
                    }
                }
                startDate = DateUtil.addDate(startDate);
                startStr = DateUtil.dataToYyyyMmDd(startDate);
            }
        } else {
            //当开始时间和结束时间同时不存在时，根据typeId 筛选
            List<CharteredJoinType> charteredJoinType = CharteredJoinType.dao.find("select * from chartered_join_type where type_id = ?", typeId);
            for (CharteredJoinType tt : charteredJoinType) {
                charteredId.add(Integer.parseInt(tt.getCharteredId()+""));
            }
        }
        if(charteredId.size()<=0){
            charteredId.add(0);
        }
        /** todo 剔除已存在订单的司机 */
        if(orderBy>1){
            helper.addEqualsCondition("city_id",cityId);
            helper.addCondition("reception_number", ">=", receptionNumber);
            helper.addIsNullCondition("delete_time");
            helper.addInCondition("id", charteredId);
            List<Object> para = new ArrayList<>();
            if(StrKit.notNull(helper.getQueryParas()) && helper.getQueryParas().length>0){
                for(Object tt :helper.getQueryParas()){
                    if(tt.equals("("+ StringUtils.join(charteredId, ",")+")")){
                           continue;
                    }
                    para.add(tt);
                }
            }
            para.add(getPageNumber()*getPageSize()-getPageSize());
            para.add(getPageSize());
            String tt = helper.getSqlExceptSelect();
            List<Chartered> list = Chartered.dao.find(helper.getSqlSelect()+tt+" LIMIT ?,?", para.toArray());
            List<Chartered> listTotal = Chartered.dao.find(helper.getSqlSelect()+tt,helper.getQueryParas());
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("ReturnCode",1);
            map.put("TotalPage",Math.ceil((double)listTotal.size()/(double)getPageSize()));
            map.put("TotalRow",listTotal.size());
            map.put("PageNumber",getPageNumber());
            map.put("PageSize",getPageSize());
            map.put("DataList",list);
            renderJson(map);
            return;
        }
        helper.addInCondition("id", charteredId);
        helper.addEqualsCondition("city_id",cityId);
        helper.addCondition("reception_number", ">=", receptionNumber);
        helper.addIsNullCondition("delete_time");
        Page<Chartered> page = Chartered.dao.paginate(getPageNumber(), getPageSize(), helper.getSqlSelect(), helper.getSqlExceptSelect(), helper.getQueryParas());
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("ReturnCode",1);
        map.put("TotalPage",page.getTotalPage());
        map.put("TotalRow",page.getTotalRow());
        map.put("PageNumber",page.getPageNumber());
        map.put("PageSize",page.getPageSize());
        map.put("DataList",page.getList());
        renderJson(map);
    }

    /**
     * 返回chartered详细信息以及他的好评平均分
     */
    public void getDetail() {
        Long targetId = getParaToLong("targetId");//被评论者的id
        Chartered chartered = Chartered.dao.findById(targetId);
        List<ContentEvaluate> evaluates = ContentEvaluate.dao.find("select * from content_evaluate where type_id = 24 and target_id = ?", targetId);
        float score = 0F;
        int i = 0;
        for (ContentEvaluate tt : evaluates) {
            score = tt.getScore() + score;
            i++;
        }
        if (score != 0F) {
            score = NumberFormatterUtil.floatLengthController(score / i, 1);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("score", score);
        map.put("target", chartered);
        returnSuccessJson(map);
    }
}
